package br.edu.ifrn.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import br.edu.ifrn.beans.Admin;
import br.edu.ifrn.persistencia.AdminDAO;

public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	HttpSession sessao;
	AdminDAO dao = new AdminDAO();

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		sessao = req.getSession();
		addAdmin(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		sessao = req.getSession();
		logar(req, resp);
	}

	private void addAdmin(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RequestDispatcher jsp;

		if (req.getParameter("senha1").equals(req.getParameter("senha2"))) {
			Admin admin = new Admin();

			admin.setMatricula(req.getParameter("matricula"));
			admin.setSenha(req.getParameter("senha1"));

			dao.inserirAdmin(admin);
			

			String mensagem = "Cadastro realizado com sucesso";
			sessao.setAttribute("mensagem", mensagem);

			jsp = req.getRequestDispatcher("admins.jsp");
			jsp.forward(req, resp);

		} else {
			String erroAdmin = "As senhas digitadas foram diferentes";
			sessao.setAttribute("erroAdmin", erroAdmin);
			jsp = req.getRequestDispatcher("novoadmin.jsp");
			jsp.forward(req, resp);
		}
	}

	private void logar(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RequestDispatcher jsp;
		Admin admin = dao.logar(req.getParameter("matricula"), req
				.getParameter("senha1"));
		if (admin == null) {
			String erroAdmin = "Usuario Invalido";
			sessao.setAttribute("erroAdmin", erroAdmin);
			jsp = req.getRequestDispatcher("admin.jsp");
			jsp.forward(req, resp);
		} else {
			sessao.removeAttribute("erroAdmin");
			sessao.setAttribute("admin", admin);
			String mensagem = "Bem-vindo";
			sessao.setAttribute("mensagem", mensagem);
			jsp = req.getRequestDispatcher("admins.jsp");
			jsp.forward(req, resp);
		}
	}
}
